# -*- coding: utf-8 -*-
from imutils.video import VideoStream
from imutils.video import FPS
import numpy as np
import time
import cv2
from kafka import KafkaConsumer
import sys,avro
from avro.io import DatumWriter, BinaryEncoder,DatumReader
from io import BytesIO
from avro.schema import Parse
from avro.io import DatumReader, BinaryDecoder
import pickle




from detection.det_model import det_model

def showCam(server, topic, window_name):
    schema = avro.schema.parse(open("avro/init_kafka_key.avsc", "rb").read())

    consumer = KafkaConsumer(
        topic,
        bootstrap_servers=[server])

    #fps = FPS().start()

    for msg in consumer:
        bytes_reader = BytesIO(msg.value)
        decoder = BinaryDecoder(bytes_reader)
        reader = DatumReader(schema)
        obj = reader.read(decoder)
        #print(obj)

        decoded = np.frombuffer(obj['stream'], np.uint8)
        img = decoded.reshape((int)(decoded.size / (400 * 3)), 400, 3)

        dets = pickle.loads(obj['dets'])
        for det in dets:
            det = list(map(int, det))
            # todo 画框
            cv2.rectangle(img, (det[0], det[1]),(det[2], det[3]), (0, 0, 255), 2)

        cv2.namedWindow(window_name, flags=cv2.WINDOW_FREERATIO)
        cv2.imshow(window_name, img)

        key = cv2.waitKey(1) & 0xFF
        if key == ord("q"):
            break
    cv2.destroyAllWindows()





if __name__ == '__main__':
    server = 'kafka:9092'
    topic = 'out'
    window_name = 'fire'
    showCam(server, topic, window_name)

